<template>
  <div class="collect-comp flex bd-top">
    <div class="left bd-right pr-10">
      <!-- 搜索 -->
      <div class="search">
        <n-input type="text" placeholder="搜索" v-model:value="keyword">
          <template #prefix>
            <n-icon size="20">
              <SearchOutline></SearchOutline>
            </n-icon>
          </template>
        </n-input>
      </div>

      <!-- 分类 -->
      <ul class="type-list">
        <li
          class="item hover click"
          :class="i === typeIndex ? 'active' : ''"
          v-for="(v, i) in types"
          :key="i"
          @click="onTypeChange(v, i)"
        >
          <div class="flex flex-center mr-10">
            <img :src="v.icon" />
          </div>

          <div>
            {{ v.label }}
          </div>
        </li>
      </ul>
    </div>

    <div class="right flex-1">
      <div class="p-10 cl-basic">
        全部{{ types[typeIndex]?.total || 0 }}条收藏
      </div>

      <ScrollView
        style="height: 500px"
        :status="types[typeIndex].status"
        @load="getCollectList"
      >
        <ul class="collect-list">
          <li
            class="item hover-item"
            :class="props.config.type === 2 ? 'click' : ''"
            v-for="(v, i) in types[typeIndex].list"
            :key="i"
            @contextmenu="handleContextMenu($event, v)"
            @click="mitt.emit('sendMessage', v)"
          >
            <!-- 消息类型 -->
            <template v-if="v.type === 1">
              <div class="flex flex-cb">
                <div class="mr-10">
                  <BaseImage class="kang-avatar" :src="v.thumbUrl"></BaseImage>
                </div>

                <div class="flex-1 mr-10">
                  <div class="fz-14 fw-bold">{{ v.origin }}</div>
                  <div class="fz-12 cl-basic hide-1">{{ v.title }}</div>
                </div>

                <div class="fz-10 cl-second">
                  {{ dayjs(v.timestamp).format('MM/DD') }}
                </div>
              </div>
            </template>

            <!-- 图片、视频 -->
            <template v-else-if="[3, 6].includes(v.type)">
              <div>
                <div v-if="v.type === 3">
                  <img
                    style="max-width: 140px; max-height: 140px"
                    :src="v.url"
                  />
                </div>

                <div v-else-if="v.type === 6">
                  <video
                    style="max-width: 140px;"
                    :src="v.url"
                    controls
                  ></video>
                </div>

                <div class="flex flex-cc flex-rb">
                  <div class="fz-12 cl-basic hide-1">
                    {{ v.origin }}
                  </div>
                  <div class="fz-10 cl-second">
                    {{ dayjs(v.timestamp).format('MM/DD') }}
                  </div>
                </div>
              </div>
            </template>

            <!-- 文件 -->
            <template v-else-if="v.type === 5">
              <div class="fz-15 fw-bold">{{ getFileInfo(v)?.name }}</div>

              <div class="flex flex-ct flex-rb">
                <div class="flex flex-cc fz-12 cl-basic">
                  <div class="mr-5">{{ getFileInfo(v)?.type }}</div>
                  <div>{{ getFileInfo(v)?.size }}MB</div>
                </div>

                <div>
                  <img
                    style="width: 30px"
                    :src="getFileIconUrl(getFileInfo(v)?.type)"
                  />
                </div>
              </div>

              <div class="flex flex-cc flex-rb">
                <div class="fz-12 cl-basic hide-1">
                  {{ v.origin }}
                </div>
                <div class="fz-10 cl-second">
                  {{ dayjs(v.timestamp).format('MM/DD') }}
                </div>
              </div>
            </template>
          </li>
        </ul>
      </ScrollView>
    </div>

    <!-- 下拉菜单 -->
    <n-dropdown
      style="width: 150px"
      placement="bottom-start"
      trigger="manual"
      :x="d.x"
      :y="d.y"
      :options="d.options"
      :show="d.visible"
      :on-clickoutside="onClickOutside"
      @select="handleSelect"
    ></n-dropdown>
  </div>
</template>

<script setup>
import { ref, h, nextTick, watch } from 'vue'
import { NImage } from 'naive-ui'
import dayjs from 'dayjs'
import mitt from '@/kang/js/mitt'
import api from '@/kang/js/api'
import { getImageUrl, getFileIconUrl } from '@/kang/js/utils'
import { SearchOutline } from '@vicons/ionicons5'

const props = defineProps({
  config: {
    type: Object,
    default: {},
  },
})

const keyword = ref('')
const timer = ref(null)

const typeIndex = ref(0)
const types = ref([
  {
    label: '全部收藏',
    icon: getImageUrl('icon_collect_all'),
    list: [],
    status: 0,
    value: '',
  },
  {
    label: '图片与视频',
    icon: getImageUrl('icon_collect_media'),
    list: [],
    status: 0,
    value: 3,
  },
  {
    label: '文件',
    icon: getImageUrl('icon_collect_file'),
    list: [],
    status: 0,
    value: 5,
  },
])

// 下拉框
const d = ref({
  x: 0,
  y: 0,
  visible: false,
  options: [
    {
      label: '删除',
      key: 'delete',
      icon: renderIcon(getImageUrl('icon_delete_message')),
    },
  ],
})

watch(
  () => keyword.value,
  () => {
    clearTimeout(timer.value)
    timer.value = setTimeout(() => {
      getCollectList(true)
      clearTimeout(timer.value)
    }, 300)
  },
  {
    immediate: true,
  }
)

getCollectList(false)

// 获取收藏列表
async function getCollectList(isRefresh = false) {
  try {
    const item = types.value[typeIndex.value]

    // 刷新
    if (isRefresh) {
      item.list = []
    }

    if (!isRefresh && item.status !== 0) {
      return
    }

    const params = {
      keyword: keyword.value,
      types: item.value,
      count: 10,
    }

    if (item.list.length) {
      params.lastId = item.list[item.list.length - 1].id
    }

    item.status = 1
    const { code, data } = await api.getCollectList(params)
    item.status = 0

    if (code === 200) {
      item.list = isRefresh ? data.items : [...item.list, ...data.items]
      item.total = data?.total || 0

      if (item.list.length === 0) {
        item.status = 4
      } else if (data.hasMore) {
        item.status = 0
      } else {
        item.status = 2
      }
    } else {
      item.status = 3
    }
  } catch (err) {
    item.status = 3
  }
}

// 取消收藏
async function deleteCollect() {
  const params = {
    id: d.value.item.id,
  }

  d.value.visible = false
  const { code } = await api.deleteCollect(params)

  if (code === 200) {
    const list = types.value[typeIndex.value].list
    const index = list.findIndex((v) => v.id === d.value.item.id)
    list.splice(index, 1)
    $message.success('删除成功')
    mitt.emit('updateFirstCollectData')
  }
}

function onTypeChange(v, i) {
  typeIndex.value = i
  getCollectList(true)
}

function handleContextMenu(e, v) {
  e.preventDefault()
  d.value.visible = false
  d.value.item = v
  nextTick().then(() => {
    d.value.visible = true
    d.value.x = e.clientX
    d.value.y = e.clientY
  })
}

function handleSelect(e) {
  if (e === 'delete') {
    deleteCollect()
  }
}

function onClickOutside() {
  d.value.visible = false
}

function getFileInfo(e) {
  let { title, data } = e
  const parsedData = JSON.parse(data)

  // 提取文件名和扩展名
  const lastDotIndex = title.lastIndexOf('.')
  const name = lastDotIndex !== -1 ? title.substring(0, lastDotIndex) : title
  const type =
    lastDotIndex !== -1 ? title.substring(lastDotIndex + 1).toUpperCase() : ''

  // 文件大小
  const size = (parsedData.size / (1024 * 1024)).toFixed(2)

  return {
    name,
    type,
    size,
  }
}

function renderIcon(icon) {
  return () => {
    return h(NImage, {
      src: icon,
      width: '20',
      height: '20',
      previewDisabled: true,
    })
  }
}
</script>

<style lang="scss" scoped>
.collect-comp {
  .left {
    width: 210px;

    .search {
      padding: 10px 0;

      :deep(.n-input) {
        background-color: var(--color-bg);
        border-radius: 10px;

        .n-input__border {
          display: none;
        }
      }
    }

    .type-list {
      .item {
        display: flex;
        align-items: center;
        height: 40px;
        padding: 0 10px;

        img {
          width: 20px;
        }

        &.active {
          background-color: var(--color-bg);
        }
      }
    }
  }

  .right {
    .collect-list {
      .item {
        padding: 10px;
        &:not(:last-child) {
          border-bottom: 1px solid var(--color-border);
        }
      }
    }
  }
}
</style>
